package com.cooksys.film_rental.bo.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cooksys.film_rental.bo.CityBo;
import com.cooksys.film_rental.bo.CountryBo;
import com.cooksys.film_rental.dao.CityDao;
import com.cooksys.film_rental.model.Address;
import com.cooksys.film_rental.model.City;
import com.cooksys.film_rental.model.Country;

@Service("CityBo")
public class CityBoImpl implements CityBo {

	@Autowired(required = true)
	CityDao cityDao;

	@Autowired
	CountryBo countryBo;

	@Override
	public City save(City city) {
		return this.cityDao.save(city);
	}

	@Override
	public void update(City city) {
		this.cityDao.update(city);
	}

	@Override
	public void delete(City city) {
		this.cityDao.delete(city);
	}

	@Override
	public City getCityByCityId(Short cityId) {
		return this.cityDao.getCityByCityId(cityId);
	}

	@Override
	public City getCityByCityId(String cityId) {
		try {

			Short cityIdAsShort = Short.valueOf(cityId);
			return this.getCityByCityId(cityIdAsShort);

		} catch (NumberFormatException e) {

			System.err
					.println("Could not parse Short value for cityId from string: "
							+ cityId);
			e.printStackTrace();
			System.err.println("Returning null value...");
			return null;

		}
	}

	@Override
	public City getCityByAddress(Address address) {
		return this.cityDao.getCityByAddress(address);
	}

	@Override
	public List<City> searchCitiesByCountry(Country country) {
		return this.cityDao.searchCitiesByCountry(country);
	}

	@Override
	public List<City> searchCitiesByPartialCityName(String partialCityName) {
		return this.cityDao.searchCitiesByPartialCityName(partialCityName);
	}

	@Override
	public List<City> getAllCities() {
		return this.cityDao.getAllCities();
	}

	@Override
	public void saveOrUpdate(City city) {
		this.cityDao.saveOrUpdate(city);

	}

	@Override
	public City matchCityToDatabase(City city, Country country) {

		City result = null;
		
		if(city.getCityId() != null){
			
			result = this.getCityByCityId(city.getCityId());
			
		}
		
		if(result == null){
			
			result = this.cityDao.getCityByInfoAndCountry(city.getCity(), country);
			
		}
		
		return result;
		
	}

}
